/*
 * Powered By [rapid-framework]
 * Web Site: http://www.rapid-framework.org.cn
 * Google Code: http://code.google.com/p/rapid-framework/
 */


package com.company.project.controller;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.io.StringWriter;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;

import cn.li.controller.Person;
import cn.org.rapid_framework.page.Page;
import cn.org.rapid_framework.page.PageRequest;

import javacommon.base.*;


import com.company.project.model.*;

import com.company.project.service.*;
import com.thoughtworks.xstream.XStream;

/**
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 * 定义标准的rest方法以对应实体对象的操作,以达到统一rest的方法名称,
 * 还可以避免子类需要重复编写@RequestMapping annotation.
 * 
 * 子类要实现某功能只需覆盖下面的方法即可.
 * 注意: 覆盖时请使用@Override,以确保不会发生错误
 * <pre>
 * /userinfo                => index()  
 * /userinfo/new            => _new()  
 * /userinfo/{id}           => show()  
 * /userinfo/{id}/edit      => edit()  
 * /userinfo        POST    => create()  
 * /userinfo/{id}   PUT     => update()  
 * /userinfo/{id}   DELETE  => delete()  
 * /userinfo        DELETE  => batchDelete() 
 * /userinfo/lqz     lqz 
 * </pre>
 * @author badqiu
 */

@Controller
@RequestMapping("/userinfo")
public class UserInfoController extends BaseRestSpringController<UserInfo,java.lang.Long>{
	//默认多列排序,example: username desc,createTime asc
	protected static final String DEFAULT_SORT_COLUMNS = null; 
	
	private UserInfoManager userInfoManager;
	
	private final String LIST_ACTION = "redirect:/userinfo";
	
	private MockHttpServletRequest request;

	private MockHttpServletResponse response;

	@Resource
	private AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter;
		
	/** 
	 * 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性
	 **/
	public void setUserInfoManager(UserInfoManager manager) {
		this.userInfoManager = manager;
	}
	
	/** 列表 */
	@Override
	public ModelAndView index(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) {
		PageRequest<Map> pageRequest = newPageRequest(request,DEFAULT_SORT_COLUMNS);
		//pageRequest.getFilters(); //add custom filters
		
		Page page = this.userInfoManager.findByPageRequest(pageRequest);
		
		ModelAndView result = toModelAndView(page, pageRequest);
		result.addObject("userInfo",userInfo);
		result.setViewName("/userinfo/list");
		return result;
	}
	
	/** 进入新增 */
	@Override
	public ModelAndView _new(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
		return new ModelAndView("/userinfo/new","userInfo",userInfo);
	}
	
	/** 显示 */
	@Override
	public ModelAndView show(@PathVariable java.lang.Long id) throws Exception {
		UserInfo userInfo = new UserInfo();//(UserInfo)userInfoManager.getById(id);
		userInfo.setAge(3);
		return new ModelAndView("/userinfo/show","userInfo",userInfo);
	}
	
	/** 编辑 */
	@Override
	public ModelAndView edit(@PathVariable java.lang.Long id) throws Exception {
		UserInfo userInfo = new UserInfo();//(UserInfo)userInfoManager.getById(id);
		userInfo.setAge(3);
		return new ModelAndView("/userinfo/edit","userInfo",userInfo);
	}
	
	/** 保存新增 */
	@Override
	public ModelAndView create(HttpServletRequest request,HttpServletResponse response,UserInfo userInfo) throws Exception {
		//userInfoManager.save(userInfo);
		return new ModelAndView(LIST_ACTION);
	}
	
	/** 保存更新 */
	@Override
	public ModelAndView update(@PathVariable java.lang.Long id,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		UserInfo userInfo = new UserInfo();//(UserInfo)userInfoManager.getById(id);
		bind(request,userInfo);
		//userInfoManager.update(userInfo);
		return new ModelAndView(LIST_ACTION);
	}
	
	/** 删除 */
	@Override
	public ModelAndView delete(@PathVariable java.lang.Long id) {
		//userInfoManager.removeById(id);
		return new ModelAndView(LIST_ACTION);
	}

	/** 批量删除 */
	@Override
	public ModelAndView batchDelete(java.lang.Long[] items) {
		for(int i = 0; i < items.length; i++) {
			//userInfoManager.removeById(items[i]);
		}
		return new ModelAndView(LIST_ACTION);
	}
	
	@RequestMapping(value="/lqz")
	public ModelAndView lqz()throws Exception{
		System.out.println("create..controller...............");
		System.out.println("create {}"+userInfoManager);
		HashMap<String,Object> model = new HashMap<String,Object>();
		model.put("success", "true");
		return new ModelAndView("msg",model );
	}
	
	// ,@RequestBody UserInfo userInfo  增加这个就报错
	@RequestMapping(value="{pageNumber}/{pageSize}")
	public ModelAndView list(@PathVariable("pageNumber") int pageNumber,
			@PathVariable("pageSize") int pageSize) throws Exception{
		logger.info("----------------------"+pageNumber);
		System.out.println("create..controller...............");
		System.out.println("create {}"+userInfoManager);
		HashMap<String,Object> model = new HashMap<String,Object>();
		model.put("success", "true");
		return new ModelAndView("msg",model );
	}
	
	@RequestMapping(value = "test/{id}", method = RequestMethod.GET)
	   public String show(@PathVariable("id") Long id, ModelMap modelMap) {
		  System.out.println(id+"Identifier must be provided.");
		  UserInfo userInfo  =  new UserInfo();
		  userInfo.setUserId(1L);
		  userInfo.setAge(2);
		  //userInfo.setBirthDate(new Date(""));
		  userInfo.setUsername("liangqz");
	      modelMap.addAttribute("userInfo", new UserInfo());
	      return "person/show";
	   }

	
	
	protected void jsonPostInit() {
		addJsonHeader();
		request.setMethod(RequestMethod.POST.toString());
	}

	protected void jsonGetInit() {
		addJsonHeader();
		request.setMethod(RequestMethod.GET.toString());
	}

	protected void jsonPutInit() {
		addJsonHeader();
		request.setMethod(RequestMethod.PUT.toString());
	}

	protected String toJson(Object o) throws Exception {
		System.out.println("toJson...............");
		StringWriter sw = new StringWriter();
		ObjectMapper mapper = new ObjectMapper();
		System.out.println("toJson......start.........");
		mapper.writeValue(sw, o);
		System.out.println("toJson.......end......");
		System.out.println("sw--- "+sw.toString());
		return sw.toString();
	}
	
	protected String toXml(Object o)throws Exception{
		XStream xstream = new XStream();
		xstream.autodetectAnnotations(true);
		return xstream.toXML(o);
	}

	private void addJsonHeader() {
		init();
		request.addHeader("Accept", "application/json, text/javascript, */*");
		request.addHeader("Content-Type", "application/json; charset=UTF-8");
	}


	private void addXmlHeader() {
		init();
		request.addHeader("Accept", "application/xml, text/xml, */*");
		request.addHeader("Content-Type", "application/xml; charset=UTF-8");
	}

	private void init() {
		request = new MockHttpServletRequest();
		request.setCharacterEncoding("UTF-8");
		response = new MockHttpServletResponse();
	}
	
	protected void xmlGetInit() {
		addXmlHeader();
		request.setMethod(RequestMethod.GET.toString());
	}

	protected void xmlPostInit() {
		addXmlHeader();
		request.setMethod(RequestMethod.POST.toString());
	}

	protected void xmlPutInit() {
		addXmlHeader();
		request.setMethod(RequestMethod.PUT.toString());
	}
	
}

